clear all 
cd "~\Data\Open_Close_Auctions"

use auction_price_impact2021.dta, clear 

keep if year(date)>2011

merge 1:1 permno date using merged_permno_date_from_step2_sample_noAmex.dta

keep if _merge==3

merge 1:1 permno date using merged_permno_date.dta

keep if _merge==3

sort permno date
xtset permno date

rename imbalance_qty0 Imbalance_Qty0
rename imbalance_open Imbalance_open
rename imbalance_side_open Imbalance_side_open
rename imbalance_side0 Imbalance_side0
rename osize OSize 
rename csize CSize

gen pct_oi=(Imbalance_Qty0)/adv_10d
drop if pct_oi>10


gen subsample_group=1 if !missing(sp500_flag)
replace subsample_group=2 if missing(subsample_group) & inlist(me_group_ff, 6,7,8,9,10)
replace subsample_group=3 if missing(subsample_group) & inlist(me_group_ff,2,3,4,5)
replace subsample_group=4 if missing(subsample_group) & inlist(me_group_ff,1)

gen signed_pct_open_oi=Imbalance_open/adv_10d if inlist(Imbalance_side_open, "B")
replace signed_pct_open_oi=-1*Imbalance_open/adv_10d if inlist(Imbalance_side_open, "S")
replace signed_pct_open_oi=0 if missing(signed_pct_open_oi)


* signed close oi 
gen signed_pct_oi1=pct_oi  if inlist(Imbalance_side0, "B")
replace signed_pct_oi1=-1*pct_oi if Imbalance_side0=="S"
replace signed_pct_oi1=0 if missing(signed_pct_oi1)
gen closing_auction_oib=signed_pct_oi1


gen abs_open_oib=abs(signed_pct_open_oi)
gen abs_close_oib=abs(closing_auction_oib)

gen open_volume= (Imbalance_open+paired_open)/adv_10d
gen close_volume=(Imbalance_Qty0+paired_qty0)/adv_10d
replace open_volume=0 if missing(open_volume)
replace close_volume=0 if missing(close_volume)



gen dow = dow(date)
gen Friday=1 if dow==5
replace Friday=0 if missing(Friday)

gen EA_dummy1=0 if missing(EA_dummy)
replace EA_dummy1=1 if missing(EA_dummy1)


*******************Table 2 summary statistics************************
eststo clear
estpost tabstat open_volume, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)
estpost tabstat open_volume if Friday==1, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)
estpost tabstat open_volume if EA_dummy1==1, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)


*******************Table 4 summary statistics************************
eststo clear
estpost tabstat close_volume, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)
estpost tabstat close_volume if Friday==1, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)
estpost tabstat close_volume if EA_dummy1==1, by(subsample_group)  stat(mean sd p10 p50 p90) columns(stat)

